package nsq_mall

import (
	sqlc "bp/db/sqlc"
	"bp/internal/util"
	"context"
	"fmt"
)

func GetBizCancelTopic() string {
	return fmt.Sprintf("%s-biz_cancel", appID)
}

type BizCancelNotification struct {
	OutTransNo string `json:"biz_no"`
	Ts         int64  `json:"timestamp"`
}

// HandleOrderCancel 处理商城系统的订单取消消息(按交易号-付款前)
func (s *NsqMallComServiceImp) HandleBizCancel(ctx context.Context, q *sqlc.Queries, ptr *BizCancelNotification) (err error) {
	slog := util.NewContextLogger(ctx, s.slog)
	outTransNo := ptr.OutTransNo
	err = s.entityHub.OffTransactionService.DisableOffTransactionsByOutTransNo(ctx, q, outTransNo)
	if err != nil {
		return
	}

	err = s.entityHub.OffTransactionService.DisableOffTransactionDetailsByOutTransNo(ctx, q, outTransNo)
	if err != nil {
		return
	}

	err = s.entityHub.OffTransactionService.DisableOffTransactionOfferItemStatsByOutTransNo(ctx, q, outTransNo)
	if err != nil {
		return
	}

	err = s.entityHub.OffApportionmentService.DisableOffApportionmentsByOutTransNo(ctx, q, outTransNo)
	if err != nil {
		return
	}

	// 解锁会员优惠券
	err = s.entityHub.MemberCouponService.NormalizeMemberCouponsByOutTransNo(ctx, q, outTransNo)
	if err != nil {
		return
	}
	slog.Infof("HandleBizCancel-外部交易(%s)-解锁会员优惠券 ok", outTransNo)
	return
}
